package hflyeer.o2o.web.controller;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.fasterxml.jackson.databind.ObjectMapper;

import hflyeer.o2o.biz.service.AreaService;
import hflyeer.o2o.biz.service.ShopCategoryService;
import hflyeer.o2o.biz.service.ShopService;
import hflyeer.o2o.model.dto.ShopExecution;
import hflyeer.o2o.model.entity.Area;
import hflyeer.o2o.model.entity.PersonInfo;
import hflyeer.o2o.model.entity.Shop;
import hflyeer.o2o.model.entity.ShopCategory;
import hflyeer.o2o.util.ImageUtils;
import hflyeer.o2o.util.KaptchaUtils;

@Controller
@RequestMapping("/shopadmin")
public class ShopController {

	private ObjectMapper mapper = new ObjectMapper();

	@Autowired
	private ShopService shopService;
	@Autowired
	private ShopCategoryService shopCategoryService;
	@Autowired
	private AreaService areaService;

	// 日志
	private static final Logger logger = LoggerFactory.getLogger(ShopController.class);

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	@ResponseBody
	/**
	 * 店铺注册
	 * 
	 * @param request
	 * @return
	 */
	private Map<String, Object> registerShop(HttpServletRequest request) {
		// 记录处理结果
		Map<String, Object> map = new HashMap<>();

		// 验证输入的验证码是否正确
		String code = request.getParameter("kaptcha");
		String sysCode = (String) request.getSession()
				.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		boolean b = KaptchaUtils.checkKeptcha(code, sysCode);
		logger.debug("系统验证码：" + sysCode);
		logger.debug("前台输入验证码：" + code);
		if (!b) {
			map.put("success", false);
			map.put("msg", "验证码输入错误");
			return map;
		}
		// 获取店铺信息并转化为对应实体类
		String shopInfo = request.getParameter("shopInfo");
		Shop shop = null;
		try {
			shop = mapper.readValue(shopInfo, Shop.class);
		} catch (Exception e) {
			map.put("success", false);
			map.put("msg", e.getMessage());
			e.printStackTrace();
			return map;
		}
		// 解析图片流
		File shopImg = null;
		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 判断是否有文件上传
		if (commonsMultipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
			MultipartFile multipartFile = multipartHttpServletRequest.getFile("shopImg");
			shopImg = ImageUtils.transferCommonsMultipartFileToFile(multipartFile);
			// 会在本地中生成多余文件，需要删除
			shopImg.delete();
		} else {
			map.put("success", false);
			map.put("msg", "上传图片不能为空");
			return map;
		}

		// 注册店铺
		if (shop != null && shopImg != null) {
			// TODO from Session get ownerId
			shop.setOwnerId(1L);
			shopService.addShop(shop, shopImg);
			map.put("success", true);
			map.put("msg", "注册成功	");
		} else {
			map.put("success", false);
			map.put("msg", "请输入店铺信息");
		}

		return map;
	}

	@RequestMapping(value = "/toregister", method = RequestMethod.GET)
	@ResponseBody
	/**
	 * 获取店铺注册所属地区和店铺分类
	 * 
	 * @return
	 */
	private Map<String, Object> toRegisterShop() {
		Map<String, Object> map = new HashMap<>();
		// 获取所有地区
		List<Area> areaList = areaService.getAreas();
		// 获取所有店铺分类
		List<ShopCategory> shopCategoryList = shopCategoryService.getShopCategorys();
		try {
			Map<String, Object> dataMap = new HashMap<>();
			dataMap.put("area", areaList);
			dataMap.put("shopCategory", shopCategoryList);
			map.put("success", true);
			map.put("data", dataMap);
		} catch (Exception e) {
			map.put("success", false);
			map.put("msg", e.getMessage());
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 店铺修改
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/modify",method=RequestMethod.POST)
	@ResponseBody
	private Map<String, Object> modifyShop(HttpServletRequest request) {
		// 记录处理结果
		Map<String, Object> map = new HashMap<>();

		// 获取店铺信息并转化为对应实体类
		String shopInfo = request.getParameter("shopInfo");
		Shop shop = null;
		try {
			shop = mapper.readValue(shopInfo, Shop.class);
		} catch (Exception e) {
			map.put("success", false);
			map.put("msg", e.getMessage());
			e.printStackTrace();
			return map;
		}
		// 解析图片流
		File shopImg = null;
		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 判断是否为文件上传
		if (commonsMultipartResolver.isMultipart(request)) {
			MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
			MultipartFile multipartFile = multipartHttpServletRequest.getFile("shopImg");
			if(multipartFile!=null)
				shopImg = ImageUtils.transferCommonsMultipartFileToFile(multipartFile);
		}

		// 更新店铺
		if (shop != null && shop.getShopId() != 0) {
			// TODO from Session get ownerId
			shop.setOwnerId(1L);
			shopService.editShop(shop, shopImg);
			map.put("success", true);
			map.put("msg", "修改成功	");
		} else {
			map.put("success", false);
			map.put("msg", "更新店铺失败");
		}

		return map;
	}

	/**
	 * 获取店铺列表
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/shoplist", method = RequestMethod.GET)
	@ResponseBody
	private Map<String, Object> getShopList(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<>();
		// 获取分页参数
		int pageNum;
		int pageSize;
		try {
			pageNum = Integer.parseInt(request.getParameter("pageNum"));
			pageSize = Integer.parseInt(request.getParameter("pageSize"));
		} catch (Exception e) {
			pageNum = 1;
			pageSize = 5;
		}

		// TODO delete the code
		PersonInfo person = new PersonInfo();
		person.setUserId(1L);
		person.setName("test");
		request.getSession().setAttribute("USER", person);

		// 获取用户Id
		person = (PersonInfo) request.getSession().getAttribute("USER");

		// 设置获取条件
		Shop shopCondition = new Shop();
		shopCondition.setOwnerId(person.getUserId());

		ShopExecution shopExecution = shopService.getShopList(shopCondition, pageNum, pageSize);
		map.put("data", shopExecution);
		return map;
	}

	/**
	 * 通过id获取单个店铺信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getshop", method = RequestMethod.GET)
	@ResponseBody
	private Map<String, Object> getShopById(HttpServletRequest request) {
		request.setAttribute("pageSize", 1);
		request.setAttribute("pageNum", 1);
		
		return getShopList(request);
	}
}
